package com.test.shop.product.service.impl;

import ch.qos.logback.core.util.TimeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.mysql.cj.x.protobuf.MysqlxDatatypes;
import com.test.shop.product.service.CategoryBrandRelationService;
import com.test.shop.product.vo.Catelog2Vo;
import lombok.Data;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.test.common.utils.PageUtils;
import com.test.common.utils.Query;

import com.test.shop.product.dao.CategoryDao;
import com.test.shop.product.entity.CategoryEntity;
import com.test.shop.product.service.CategoryService;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static String catalog = "catalogJSON";

    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> all = baseMapper.selectList(null);
        List<CategoryEntity> list = all.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());
        return list;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查是否被引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> path = new ArrayList<>();

        List<Long> parentPath = findParentPath(catelogId, path);

        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Override
    @CacheEvict(value = "category",key = "'getLevelCategorys'")
    public void updateCasecade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

    }
    // 代表当前方法使用缓存，没有则调用方法，放入缓存，有则直接获取缓存,
    // 自动配置：没设置key是自动生成的。value的值默认使用jdk序列化机制，将序列化后的数据存储到redis（缓存的类型）默认的过期时间是-1.
    // 手动配置：指定key,"#root.method.name"为方法名，指定

//    原理：CacheAutoConfiguration -》RedisCacheConfiguration ->自动配置了RedisCacheManager->初始化缓存->
//    每个缓存决定用什么配置。如果容器中存在RedisCacheConfiguartion则使用已有的，没有配置用默认
//    -》想修改则在容器中加一个RedisCacheConfiguration即可
    @Cacheable(cacheNames = {"category","product"},key = "#root.methodName")
    @Override
    public List<CategoryEntity> getLevelCategorys() {
        List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entities;
    }

    @Override
    @Cacheable(value = "category",key = "#root.methodName")
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        // 查出所有一级分类
        List<CategoryEntity> level1List = getParent_cid(selectList,0L);
        Map<String, List<Catelog2Vo>> parent_cid = level1List.stream().collect(Collectors.toMap(
                k -> String.valueOf(k.getCatId())
                , v -> {
                    // 根据一级分类的id获取二级分类信息
                    List<CategoryEntity> level2List = getParent_cid(selectList,v.getCatId());
                    List<Catelog2Vo> catalog2Vos = new ArrayList<>();
                    if (level2List != null) {
                        catalog2Vos = level2List.stream().map(l2 -> {
                            Catelog2Vo catelog2Vo = new Catelog2Vo(String.valueOf(v.getCatId()), null, String.valueOf(l2.getCatId()), l2.getName());
                            // 获取三级分类
                            List<CategoryEntity> level3List = getParent_cid(selectList,l2.getCatId());
                            List<Catelog2Vo.Catelog3Vo> catelog3Vos = new ArrayList<>();
                            if (level3List != null) {
                                catelog3Vos = level3List.stream().
                                        map(l3 -> new Catelog2Vo.Catelog3Vo(String.valueOf(l2.getCatId()), String.valueOf(l3.getCatId()), l3.getName()))
                                        .collect(Collectors.toList());
                            }
                            catelog2Vo.setCatalog3List(catelog3Vos);
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catalog2Vos;
                }));
        return parent_cid;
    }


    public Map<String, List<Catelog2Vo>> getCatalogJsonWithRedissonLock(){
        
        // 注意名字 锁的粒度，越小越好越快
        // 锁的粒度：具体缓存一个数据，则设置名字如 product-11-lock。粒度小，处理快
        RLock lock = redisson.getLock(catalog + "-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> dataFormDB;
        try{
            // 加锁成功，执行业务
            dataFormDB  = getDataFormDB();
        }finally{
            lock.unlock();
        }
        return dataFormDB;
    }
    public Map<String, List<Catelog2Vo>> getCatalogJsonWithRedisLock(){
        String locks = "lock";
        String uuid = UUID.randomUUID().toString();
        // 设置过期时间
        Boolean lock = redisTemplate.opsForValue().setIfAbsent(locks, uuid,30,TimeUnit.SECONDS);

        if(lock){
            Map<String, List<Catelog2Vo>> dataFormDB;
            try{
                // 加锁成功，执行业务
                dataFormDB  = getDataFormDB();
            }finally {
                // 删除锁
//            if(redisTemplate.opsForValue().get(locks).equalsIgnoreCase(uuid)){
//                redisTemplate.delete("lock");
//            }
                String script = " if(redis.call('get',KEYS[1]) == ARGV[1]) then  redis.call('del', KEYS[1])  end return 0";
                // 通过lua原子性的删除锁
                Long execute = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                        Arrays.asList(locks),
                        uuid);
            }
            return dataFormDB;
        }else{
            // 加锁失败.. 自旋重试
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonWithRedisLock();
        }
    }
    public Map<String, List<Catelog2Vo>> getCatalogJsonWithLocalLock(){
        // 从缓存中获取数据，数据都是JSON字符串，JSON支持跨平台，跨语言
        String catalogJSON = redisTemplate.opsForValue().get(catalog);

        if(StringUtils.isEmpty(catalogJSON)){
            // 缓存中没有数据
            Map<String, List<Catelog2Vo>> catalogJsonFormDB = getCatalogJsonFormDB();
            return catalogJsonFormDB;
        }
        // 将json字符串逆转出我们需要的对象
        Map<String, List<Catelog2Vo>> result  = JSON.parseObject(catalogJSON,new TypeReference<Map<String, List<Catelog2Vo>>>(){});
        return result;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFormDB() {
        // 双检锁
        synchronized (this){
            // 从缓存中获取数据，数据都是JSON字符串，JSON支持跨平台，跨语言
            String catalogJSON = redisTemplate.opsForValue().get(catalog);

            if(!StringUtils.isEmpty(catalogJSON)){
                return JSON.parseObject(catalogJSON,new TypeReference<Map<String, List<Catelog2Vo>>>(){});
            }
            // 优化
            /**
             * 将数据库的多次查询变成一次查询
             */
            List<CategoryEntity> selectList = baseMapper.selectList(null);

            // 查出所有一级分类
            List<CategoryEntity> level1List = getParent_cid(selectList,0L);
            Map<String, List<Catelog2Vo>> parent_cid = level1List.stream().collect(Collectors.toMap(
                    k -> String.valueOf(k.getCatId())
                    , v -> {
                        // 根据一级分类的id获取二级分类信息
                        List<CategoryEntity> level2List = getParent_cid(selectList,v.getCatId());
                        List<Catelog2Vo> catalog2Vos = new ArrayList<>();
                        if (level2List != null) {
                            catalog2Vos = level2List.stream().map(l2 -> {
                                Catelog2Vo catelog2Vo = new Catelog2Vo(String.valueOf(v.getCatId()), null, String.valueOf(l2.getCatId()), l2.getName());
                                // 获取三级分类
                                List<CategoryEntity> level3List = getParent_cid(selectList,l2.getCatId());
                                List<Catelog2Vo.Catelog3Vo> catelog3Vos = new ArrayList<>();
                                if (level3List != null) {
                                    catelog3Vos = level3List.stream().
                                            map(l3 -> new Catelog2Vo.Catelog3Vo(String.valueOf(l2.getCatId()), String.valueOf(l3.getCatId()), l3.getName()))
                                            .collect(Collectors.toList());
                                }
                                catelog2Vo.setCatalog3List(catelog3Vos);
                                return catelog2Vo;
                            }).collect(Collectors.toList());
                        }
                        return catalog2Vos;
                    }));

            // 将数据加入到缓存中,并将对象转换为json字符串
            String s = JSON.toJSONString(parent_cid);
            redisTemplate.opsForValue().set(catalog,s,1, TimeUnit.DAYS);
            return parent_cid;
        }

    }

    private Map<String, List<Catelog2Vo>> getDataFormDB(){

        // 从缓存中获取数据，数据都是JSON字符串，JSON支持跨平台，跨语言
        String catalogJSON = redisTemplate.opsForValue().get(catalog);

        if(!StringUtils.isEmpty(catalogJSON)){
            return JSON.parseObject(catalogJSON,new TypeReference<Map<String, List<Catelog2Vo>>>(){});
        }
        // 优化
        /**
         * 将数据库的多次查询变成一次查询
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        // 查出所有一级分类
        List<CategoryEntity> level1List = getParent_cid(selectList,0L);
        Map<String, List<Catelog2Vo>> parent_cid = level1List.stream().collect(Collectors.toMap(
                k -> String.valueOf(k.getCatId())
                , v -> {
                    // 根据一级分类的id获取二级分类信息
                    List<CategoryEntity> level2List = getParent_cid(selectList,v.getCatId());
                    List<Catelog2Vo> catalog2Vos = new ArrayList<>();
                    if (level2List != null) {
                        catalog2Vos = level2List.stream().map(l2 -> {
                            Catelog2Vo catelog2Vo = new Catelog2Vo(String.valueOf(v.getCatId()), null, String.valueOf(l2.getCatId()), l2.getName());
                            // 获取三级分类
                            List<CategoryEntity> level3List = getParent_cid(selectList,l2.getCatId());
                            List<Catelog2Vo.Catelog3Vo> catelog3Vos = new ArrayList<>();
                            if (level3List != null) {
                                catelog3Vos = level3List.stream().
                                        map(l3 -> new Catelog2Vo.Catelog3Vo(String.valueOf(l2.getCatId()), String.valueOf(l3.getCatId()), l3.getName()))
                                        .collect(Collectors.toList());
                            }
                            catelog2Vo.setCatalog3List(catelog3Vos);
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return catalog2Vos;
                }));

        // 将数据加入到缓存中,并将对象转换为json字符串
        String s = JSON.toJSONString(parent_cid);
        redisTemplate.opsForValue().set(catalog,s,1, TimeUnit.DAYS);
        return parent_cid;
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    public List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == root.getCatId()
        ).peek(categoryEntity -> categoryEntity.setChildren(getChildren(categoryEntity, all))).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());

        return children;
    }

    /**
     * 优化压力测试，一次查询所以，减少db的压力
     * @param selectList
     * @param parent_cid
     * @return
     */
    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList,Long parent_cid){
        return selectList.stream().filter(t-> t.getParentCid().equals(parent_cid)).collect(Collectors.toList());
    }
}